import { ref, watch, onMounted } from 'vue';
import type { TabView } from '@/components/SimpleTabs/index.vue';

/**
 * 用于已访问视图tabs管理
 * @param cacheKey 设置本地缓存 标识符key
 * @returns
 */
const useVisitedViews = (cacheKey: string) => {
  const activeCacheKey = cacheKey + '-active';

  const visitedViews = ref<TabView[]>([]);
  const currentView = ref<TabView>();

  onMounted(() => {
    visitedViews.value = JSON.parse(localStorage.getItem(cacheKey) as string) || [];

    currentView.value = JSON.parse(localStorage.getItem(activeCacheKey) as string) || undefined;
  });

  watch(currentView, () => {
    if (currentView.value) {
      localStorage.setItem(activeCacheKey, JSON.stringify(currentView.value));
    } else {
      localStorage.removeItem(activeCacheKey);
    }
  });

  watch(
    visitedViews,
    () => {
      if (visitedViews.value.length) {
        localStorage.setItem(cacheKey, JSON.stringify(visitedViews.value));
      } else {
        localStorage.removeItem(cacheKey);
      }
    },
    {
      deep: true,
    },
  );

  /**
   * 将视图添加到已访问的视图列表中
   * @param view
   * @returns
   */
  const addView = (view: TabView) => {
    currentView.value = view;

    if (visitedViews.value.some((v) => v.id === view.id)) {
      return;
    }

    visitedViews.value.push(view);
  };

  /**
   * 从已访问的视图列表中删除视图
   * @param view
   */
  const delView = (view: TabView) => {
    // 找到与指定视图路径匹配的视图，在已访问视图列表中删除该视图
    visitedViews.value = visitedViews.value.filter((v) => v.id !== view.id);
    // 若关闭的是当前开的tab项, 则默认打开已访问的视图中的最后一项
    if (isActive(view)) {
      toLastView(visitedViews.value, view);
    }
  };

  /**
   * 判断视图是否是打开状态
   * @param view
   * @returns
   */
  const isActive = (view: TabView) => view.id === currentView.value?.id;

  /**
   * 将视图列表中最后一项视图置于 active状态
   * @param views 已访问视图列表
   * @param view 当前操作的视图
   */
  const toLastView = (views: TabView[], view: TabView) => {
    currentView.value = views.slice(-1)[0];
  };

  return {
    visitedViews,
    currentView,
    addView,
    delView,
  };
};

export default useVisitedViews;
